package weaver.formmode.customjavacode.modeexpand.huangwm.SW003;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.customization.huangwm.dao.SW003.LoggingDao;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.DateTools;
import com.customization.huangwm.utils.HttpRequest;
import com.customization.huangwm.utils.LogTool;
import weaver.conn.RecordSet;
import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Huangwm
 * @Date 2022-05-10
 * @Version 1.0
 * @Description TODO 登記物料的時候傳入用友生成物料檔案
 **/
public class PushToNC_bsinvman extends AbstractModeExpandJavaCodeNew {
    private LogTool logTool = new LogTool("/log/SW003/huangwm/model/action/PushToNC_bsinvman", false);
    private DBTools dbTools = new DBTools();
    private DateTools dateTools = new DateTools();
    @Override
    public Map<String, String> doModeExpand(Map<String, Object> param) {
        Map<String, String> result = new HashMap<String, String>();
        BaseBean baseBean = new BaseBean();
        try {
            User user = (User) param.get("user");
            int billid = -1;//数据id
            int modeid = -1;//模块id
            RequestInfo requestInfo = (RequestInfo) param.get("RequestInfo");
            if (requestInfo != null) {
                billid = Util.getIntValue(requestInfo.getRequestid());
                modeid = Util.getIntValue(requestInfo.getWorkflowid());
                logTool.writeLog("登记物料信息  userid=" + user.getUID() + "  billid=" + billid);
                if (billid > 0 && modeid > 0) {
//                    Property[] properties = requestInfo.getMainTableInfo().getProperty();
                    Map<String, String> mainDatas = new HashMap<>();
//                    for (Property property : properties) {
//                        mainDatas.put(property.getName(), property.getValue());
//                    }
                    String eop_reqToken = baseBean.getPropValue("SW003", "eop_reqToken");
                    if (eop_reqToken.isEmpty()) {
                        eop_reqToken = "EapUfida20200630D1207F4TEST";
                    }
                    String eop_reqUrl = baseBean.getPropValue("SW003", "eop_reqUrl");
                    if (eop_reqUrl.isEmpty()) {
                        eop_reqUrl = "https://testeop.macaowater.com";
                    }
                    String sql2 = "select * from uf_003_AssteInfo where id=" + billid;
                    RecordSet rs1 = new RecordSet();
                    rs1.execute(sql2);
                    rs1.next();
                    String[] columns = rs1.getColumnName();
                    for (int i = 0; i < columns.length; i++) {
                        mainDatas.put(columns[i].toLowerCase(), rs1.getString(columns[i]));
                    }
                    //分解数据传入用友
                    Map<String, Object> reqData = new HashMap<>();
                    List<Map<String, Object>> datas = new ArrayList<>();//reqData中的data
                    Map<String, Object> data = new HashMap<>();
                    Map<String, String> invbas = new HashMap<>();
                    Map<String, String> invman = new HashMap<>();
                    RecordSet rs = new RecordSet();
                    String isAsset = mainDatas.get("isasset");
                    //invbas.put("asset", isAsset.equals("0") ? "Y" : "N");
                    invbas.put("asset", "N");
                    String assetCode = mainDatas.get("assetcode");
                    invbas.put("id", assetCode);
                    invbas.put("invcode", assetCode);
                    String assetName = mainDatas.get("assetname");
                    invbas.put("invname", replaceStr(assetName));
                    invbas.put("forinvname", replaceStr(assetName));
                    invbas.put("invshortname", replaceStr(assetName));
                    String assetDescribe = mainDatas.get("assetdescribe");
                    invman.put("memo", replaceStr(assetDescribe));//將物料描述當作備注
                    String unit = mainDatas.get("unit");
                    invbas.put("pk_measdoc", dbTools.getUnitCodeById(rs, unit));
                    String manageDep = mainDatas.get("managedep");
                    String assetModel = mainDatas.get("assetmodel");
                    invbas.put("invtype", replaceStr(assetModel));
                    String assetType = mainDatas.get("assettype");//用友物料种类
                    String assetType2 = mainDatas.get("assettype2");//EAP物料种类
                    invbas.put("pk_invcl", dbTools.getEapTypeIdCompareYY(rs, assetType2));
                    /*
                    20221013 物料新增时不会填写库存 移除逻辑
                    Float InventoryQuantity = Float.parseFloat(mainDatas.get("inventoryquantity"));
                    Float usedQuantity = Float.parseFloat(mainDatas.get("usedquantity"));
                    Float totalQuantity = Float.parseFloat(mainDatas.get("totalquantity"));
                    */
                    //invbas其他參數
                    invbas.put("setpartsflag", "N");
                    invbas.put("invspec", "");
                    invbas.put("pk_corp", "MW");
                    invbas.put("discountflag", "N");
                    invbas.put("setpartsflag", "N");
                    invbas.put("assistunit", "N");
                    invbas.put("ismngstockbygrswt", "N");
                    invbas.put("autobalancemeas", "Y");
                    invbas.put("isstorebyconvert", "N");
                    invbas.put("isretail", "N");
                    invbas.put("pk_taxitems", "9003");
                    //invman其他參數
                    invman.put("sellproxyflag", "N");
                    invman.put("planprice", "0");
                    invman.put("costprice", "0");
                    invman.put("refsaleprice", "0");
                    invman.put("consumesettleflag", "N");
                    invman.put("qualitymanflag", "N");
                    invman.put("qualityperiodunit", "2");
                    invman.put("qualitydaynum", "0");
                    invman.put("serialmanaflag", "N");
                    invman.put("wholemanaflag", "N");
                    invman.put("sealflag", "N");//是否封存
                    invman.put("accflag", "N");
                    invman.put("outtrackin", "N");
                    invman.put("negallowed", "N");
                    invman.put("iscanpurchased", "Y");
                    invman.put("iscansold", "N");
                    invman.put("issalable", "Y");
                    invman.put("isnoconallowed", "Y");

                    data.put("invbas", invbas);
                    data.put("invman", invman);
                    datas.add(data);

                    reqData.put("data", datas);
                    HttpRequest http = new HttpRequest();
                    JSONObject params = new JSONObject();
                    params.put("reqNb", http.getTimestamp());
                    params.put("reqLang", "zh");
                    params.put("reqToken", eop_reqToken);
                    params.put("reqData", reqData);
                    logTool.writeLog("---傳入用友參數如下---");
                    logTool.writeLog(JSON.toJSONString(params));
                    JSONObject json_Save = http.CallApiPost(eop_reqUrl + "/eop/eapToUfida/bsinvman", JSONObject.toJSONString(params));
                    logTool.writeLog("---傳入用友結果如下---");
                    logTool.writeLog(JSON.toJSONString(json_Save));
                    LoggingDao loggingDao = new LoggingDao();
                    loggingDao.wrtieLog("0", "/eop/eapToUfida/bsinvman", JSON.toJSONString(params), JSON.toJSONString(json_Save));
                    if (json_Save == null || !json_Save.getOrDefault("state", "-1").equals("0")) {
                        result.put("errmsg", "保存物料寫入用友失敗,请稍后编辑重新保存 " + JSON.toJSONString(json_Save));
                        result.put("flag", "false");
                        return result;
                    }else {
                        //寫入用友期初庫存
                        /*
                        20221013 期初逻辑改从仓库库存实现 移除逻辑
                        if((totalQuantity-usedQuantity)>0){
                            JSONObject params_Bill = new JSONObject();
                            params_Bill.put("reqNb", http.getTimestamp());
                            params_Bill.put("reqLang", "zh");
                            params_Bill.put("reqToken", eop_reqToken);
                            Map<String, Object> reqData_Bill = new HashMap<>();
                            List<Map<String, Object>> bill = new ArrayList<>();//reqData中的bill
                            Map<String, Object> bill_data = new HashMap<>();
                            //billHead内容
                            Map<String, Object> billHead = new HashMap<>();
                            billHead.put("id",billid);
                            billHead.put("cbilltypecode","4A");
                            billHead.put("dbilldate",dateTools.getCurrentDate());
                            billHead.put("pk_corp","MW");
                            billHead.put("vbillcode","");
                            billHead.put("cdispatcherid","21");
                            billHead.put("cdeptid",dbTools.getYyDepCode(user.getUID() + ""));
                            billHead.put("pk_calbody","MW");
                            billHead.put("cwarehouseid","02");
                            billHead.put("coperatorid",dbTools.getWorkCode(user.getUID()+""));
                            billHead.put("fbillflag","2");
                            billHead.put("vnote","期初-02倉庫");
                            //添加billhead内容
                            bill_data.put("billHead",billHead);
                            bill.add(bill_data);

                            List<Map<String, Object>> billBody = new ArrayList<>();
                            Map<String, Object> billBody_data = new HashMap<>();
                            billBody_data.put("cinventoryid",assetCode);
                            billBody_data.put("dbizdate",dateTools.getCurrentDate());
                            billBody_data.put("ninnum",(totalQuantity-usedQuantity));
                            billBody_data.put("nprice","0");
                            billBody_data.put("nmny","0");
                            //添加body内容
                            billBody.add(billBody_data);
                            bill_data.put("billBody",billBody);
                            reqData_Bill.put("bill",bill);
                            params_Bill.put("reqData",reqData_Bill);

                            logTool.writeLog("---期初入庫傳入用友參數如下---");
                            logTool.writeLog(JSON.toJSONString(params_Bill));
                            JSONObject json_Bill = http.CallApiPost(eop_reqUrl + "/eop/eapToUfida/icBillBegin", JSONObject.toJSONString(params_Bill));
                            logTool.writeLog("---期初入庫傳入用友結果如下---");
                            logTool.writeLog(JSON.toJSONString(json_Bill));
                            loggingDao.wrtieLog("0", "/eop/eapToUfida/icBillBegin", JSON.toJSONString(params_Bill), JSON.toJSONString(json_Bill));
                            if (json_Bill == null || !json_Bill.getOrDefault("state", "-1").equals("0")) {
                                //考虑回调表单数量为0？
                                result.put("errmsg", "保存物料寫入用友成功但期初入庫失敗 " + JSON.toJSONString(json_Bill));
                                result.put("flag", "false");
                                return result;
                            }
                        }
                         */
                    }
                } else {
                    result.put("errmsg", "保存動作擴展接口異常 billid为空");
                    result.put("flag", "false");
                    return result;
                }
            }
        } catch (Exception e) {
            logTool.writeLog("保存動作擴展接口異常 \n" + e.toString());
            result.put("errmsg", "保存動作擴展接口異常 \n" + e.toString());
            result.put("flag", "false");
        }
        return result;
    }

    /**
     * 根據用友接口要求 將特殊字符替換爲指定轉義字符
     * @param str
     * @return
     */
    public String replaceStr(String str){
//        String s =  str.replace("\"","&quot;").replace("\'","&apos;").replace("&","&amp;")
//                .replace("<","&lt;").replace(">","&gt;");
        String s =  "<![CDATA["+str+"]]>";
        return s;
    }
}
